

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="John Doe">
  <meta name="keywords" content="">
  
    <meta name="description" content="@[toc] 1. Java Thread多线程 Adnroid官方文档 两种方式创建并启动线程  方式一： 继承 java.lang.Thread 并重写run()  12345678910111213class myThread extends Thread&amp;#123;    &#x2F;&#x2F; 成员变量    private int num;    myThread(int num)&amp;#123;">
<meta property="og:type" content="article">
<meta property="og:title" content="Android Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo">
<meta property="og:url" content="http://example.com/2022/01/02/Android%20_%20Handler%E5%A4%9A%E7%BA%BF%E7%A8%8B%E6%B6%88%E6%81%AF%E4%BC%A0%E9%80%92%E6%9C%BA%E5%88%B6%20_%20Bundle%E5%B0%81%E8%A3%85%E6%95%B0%E6%8D%AE%20_%20Message%E6%B6%88%E6%81%AF%E5%8F%91%E9%80%81%20+Demo/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="@[toc] 1. Java Thread多线程 Adnroid官方文档 两种方式创建并启动线程  方式一： 继承 java.lang.Thread 并重写run()  12345678910111213class myThread extends Thread&amp;#123;    &#x2F;&#x2F; 成员变量    private int num;    myThread(int num)&amp;#123;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/a45eca14d1c84369b53f7e5b21eb343a.png#pic_center">
<meta property="og:image" content="https://img-blog.csdnimg.cn/637593c6e6724a9e84d409b68e35b5ac.png#pic_center">
<meta property="article:published_time" content="2022-01-02T05:21:00.000Z">
<meta property="article:modified_time" content="2022-08-22T15:42:15.938Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="Android">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/a45eca14d1c84369b53f7e5b21eb343a.png#pic_center">
  
  
  
  <title>Android Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>尤 Ni&#39;s Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Android Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        John Doe
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-01-02 13:21" pubdate>
          2022年1月2日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          92 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Android Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：1 小时前
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <p>@[toc]</p>
<h1 id="1-Java-Thread多线程"><a href="#1-Java-Thread多线程" class="headerlink" title="1. Java Thread多线程"></a>1. Java Thread多线程</h1><hr>
<p><a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/kotlin/java/lang/Thread?hl=en">Adnroid官方文档</a></p>
<p>两种方式创建并启动线程</p>
<ul>
<li>方式一： 继承 <code>java.lang.Thread</code> 并重写<code>run()</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">myThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Thread</span>&#123;<br>    <span class="hljs-comment">// 成员变量</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> num;<br>    myThread(<span class="hljs-type">int</span> num)&#123;<br>        <span class="hljs-built_in">this</span>.num = num;<br>    &#125;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-comment">//... </span><br>    &#125;<br>&#125;<br><span class="hljs-comment">// 启动线程</span><br><span class="hljs-keyword">new</span> <span class="hljs-title class_">myThread</span>(<span class="hljs-number">10</span>).start();<br></code></pre></td></tr></table></figure>

<ul>
<li>方式二：实现 <code>Runnable</code> 接口</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">myThread</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Runnable</span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> num;<br>    myThread(<span class="hljs-type">int</span> num)&#123;<br>        <span class="hljs-built_in">this</span>.num = num;<br>    &#125;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-comment">//...</span><br>    &#125;<br>&#125;<br><span class="hljs-comment">// 启动线程</span><br><span class="hljs-keyword">new</span> <span class="hljs-title class_">Thread</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">myThread</span>(<span class="hljs-number">10</span>)).start();<br></code></pre></td></tr></table></figure>


<h1 id="2-Handler"><a href="#2-Handler" class="headerlink" title="2. Handler"></a>2. Handler</h1><hr>
<p>Handler : 线程之间传递消息的即时接口，生产线程和消费线程调用以下操作使用Handler：</p>
<ul>
<li>在消息队列创建、插入或移除消息</li>
<li>在消费线程中处理消息</li>
</ul>
<p>每个Handler有一个与之相关的 Looper 和消息队列MessageQueue。</p>
<p>同一线程的多个Handler分享一个同样的消息队列，因为他们分享的Looper对象是同一个。</p>
<p>关于Handler的构造函数<a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/android/os/Handler#summary">官方文档</a></p>
<table>
<thead>
<tr>
<th align="left">函数名</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">Handler()</td>
<td align="left">已弃用</td>
</tr>
<tr>
<td align="left">Handler(Handler.Callback callback)</td>
<td align="left">已弃用</td>
</tr>
<tr>
<td align="left">Handler(Looper looper)</td>
<td align="left">使用提供的looper对象</td>
</tr>
<tr>
<td align="left">Handler(Looper looper, Handler.Callback callback)</td>
<td align="left">使用提供的looper对象和回调接口来处理消息</td>
</tr>
</tbody></table>
<p>在构造函数中，looper对象可以通过<code>Looper.myLooper()</code> 创建并获取</p>
<h1 id="3-Message"><a href="#3-Message" class="headerlink" title="3. Message"></a>3. Message</h1><hr>
<p><a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/android/os/Message?hl=en">官方文档</a></p>
<p>Message 是容纳任意数据的容器，是Handler接收与处理的消息对象。</p>
<p>生产消息发送消息给Handler，Hadnler将消息加入到消息队列中。</p>
<p>该对象提供三种信息，以便Handler和消息队列处理时使用：</p>
<ul>
<li>what 一种标识符，Hander能使用它区分不同消息，从而采取不同的处理方法</li>
<li>time 告知消息队列何时处理消息</li>
<li>target 表示哪一个Handler 应当处理消息</li>
</ul>
<p>该对象的创建方式有：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">Handler.obtainMessage();	<br>Handler.obtainMessage(<span class="hljs-type">int</span> what);<br>Handler.obtainMessage(<span class="hljs-type">int</span> what, Object obj);<br>Handler.obtainMessage(<span class="hljs-type">int</span> what, <span class="hljs-type">int</span> arg1, <span class="hljs-type">int</span> arg2);<br>Handler.obtainMessage(<span class="hljs-type">int</span> what, <span class="hljs-type">int</span> arg1, <span class="hljs-type">int</span> arg2, Object obj);<br></code></pre></td></tr></table></figure>

<p>通过Bundle对象设置消息的数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">setData</span> <span class="hljs-params">(Bundle data)</span>;<br></code></pre></td></tr></table></figure>

<h1 id="4-MessageQueue"><a href="#4-MessageQueue" class="headerlink" title="4. MessageQueue"></a>4. MessageQueue</h1><hr>
<p><a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/kotlin/android/os/MessageQueue?hl=en">官方文档</a></p>
<p>消息队列（为方便阅读，简写为MQ），以FIFO方式管理所有的<code>Message</code>对象。</p>
<p>是一个<code>LinkedList</code>集合</p>
<ul>
<li>在初始化<code>Looper</code>对象时会创建一个与之关联的MQ</li>
<li>每个线程最多只有一个MQ</li>
<li>MQ通常是由 <code>Looper</code> 管理</li>
<li>主线程创建时，会创建一个默认的<code>Looper</code>对象，从而自动创建一个MQ</li>
</ul>
<h1 id="5-Looper"><a href="#5-Looper" class="headerlink" title="5. Looper"></a>5. Looper</h1><hr>
<p><a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/android/os/Looper?hl=en">官方文档</a></p>
<p>负责从消息队列MessageQueue中读取消息，然后分发给对应的Handler处理。</p>
<p>每个线程只能管理一个Looper。</p>
<p>使用范例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">class</span> <span class="hljs-title class_">LooperThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Thread</span> &#123;<br>     <span class="hljs-keyword">public</span> Handler mHandler;<br><br>     <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>         Looper.prepare();<br><br>         mHandler = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>(Looper.myLooper()) &#123;<br>             <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">handleMessage</span><span class="hljs-params">(Message msg)</span> &#123;<br>                 <span class="hljs-comment">// process incoming messages here</span><br>             &#125;<br>         &#125;;<br><br>         Looper.loop();<br>     &#125;<br> &#125;<br></code></pre></td></tr></table></figure>

<h1 id="6-AtomicBoolean"><a href="#6-AtomicBoolean" class="headerlink" title="6. AtomicBoolean"></a>6. AtomicBoolean</h1><hr>
<p>作为 <code>java.util.concurrent.atomic</code> 包下的一个类，指原子性的Boolean类型</p>
<p>该类实现的是在多线程环境下，具有排他性，不会被打断，常用方法：</p>
<table>
<thead>
<tr>
<th align="left">方法名</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">get()</td>
<td align="left">获取当前的值返回true或false</td>
</tr>
<tr>
<td align="left">set(Boolean nueValue)</td>
<td align="left">设置新的布尔值</td>
</tr>
</tbody></table>
<p>构造方法：<code>initialValue(Boolean b)</code></p>
<h1 id="7-Handler使用总结"><a href="#7-Handler使用总结" class="headerlink" title="7. Handler使用总结"></a>7. Handler使用总结</h1><hr>
<p>首先在<code>AppCompatActivity.java</code>类中创建 $handler$ 对象，传入两个参数，第一个是 $looper$，第二个是$Callback()$接口的实现类，</p>
<p>该接口方法实现的是当线程接收到消息 $message$ 时做出的响应，在倒计时的案例里就是更新$TextView$，即显示当前的数字。</p>
<p>综上，Handler作为线程之间传递消息的接口，实现步骤为：</p>
<ul>
<li>App主类负责编写handler对象接收到消息后的处理逻辑</li>
<li>线程类负责存储handler对象，以及在run方法里编写向Handler传递消息的具体实现</li>
</ul>
<p>Handler传输的消息对象Message里的数据是通过对Java的数据类型或对象进行封装后的Bundle对象来传输的。</p>
<h1 id="8-案例"><a href="#8-案例" class="headerlink" title="8. 案例"></a>8. 案例</h1><hr>
<h2 id="8-1-倒计时"><a href="#8-1-倒计时" class="headerlink" title="8.1 倒计时"></a>8.1 倒计时</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> androidx.annotation.NonNull;<br><span class="hljs-keyword">import</span> androidx.appcompat.app.AppCompatActivity;<br><br><span class="hljs-keyword">import</span> android.os.Bundle;<br><span class="hljs-keyword">import</span> android.os.Handler;<br><span class="hljs-keyword">import</span> android.os.Looper;<br><span class="hljs-keyword">import</span> android.os.Message;<br><span class="hljs-keyword">import</span> android.view.View;<br><span class="hljs-keyword">import</span> android.widget.TextView;<br><br><span class="hljs-keyword">class</span> <span class="hljs-title class_">TimeCountThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Thread</span>&#123;<br>    <span class="hljs-keyword">private</span> Handler handler;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">int</span> timecount;<br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">TimeCountThread</span><span class="hljs-params">(Handler handler, <span class="hljs-type">int</span> timecount)</span>&#123;<br>        <span class="hljs-built_in">this</span>.handler = handler;<br>        <span class="hljs-built_in">this</span>.timecount = timecount;<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> timecount; i &gt;= <span class="hljs-number">0</span>; i--) &#123;<br>            <span class="hljs-keyword">try</span> &#123;<br>                Thread.sleep(<span class="hljs-number">1000</span>);<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>                e.printStackTrace();<br>            &#125;<br>            <span class="hljs-type">Message</span> <span class="hljs-variable">message</span> <span class="hljs-operator">=</span> handler.obtainMessage();<br>            <span class="hljs-type">Bundle</span> <span class="hljs-variable">bundle</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Bundle</span>();<br>            bundle.putInt(<span class="hljs-string">&quot;Now&quot;</span>, i);<br>            message.setData(bundle);<br>            handler.sendMessage(message);<br>        &#125;<br>    &#125;<br>&#125;<br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AppCompatActivity</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onCreate</span><span class="hljs-params">(Bundle savedInstanceState)</span> &#123;<br>        <span class="hljs-built_in">super</span>.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_main);<br>        <span class="hljs-type">TextView</span> <span class="hljs-variable">tv</span> <span class="hljs-operator">=</span> findViewById(R.id.TextView);<br>        <span class="hljs-type">Handler</span> <span class="hljs-variable">handler</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>(Looper.myLooper(), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>.Callback() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">handleMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message message)</span> &#123;<br>                tv.setText(message.getData().getInt(<span class="hljs-string">&quot;Now&quot;</span>) + <span class="hljs-string">&quot;&quot;</span>);<br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>            &#125;<br>        &#125;);<br>        <span class="hljs-keyword">new</span> <span class="hljs-title class_">TimeCountThread</span>(handler, <span class="hljs-number">100</span>).start();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="8-2-计时器"><a href="#8-2-计时器" class="headerlink" title="8.2 计时器"></a>8.2 计时器</h2><p><img src="https://img-blog.csdnimg.cn/a45eca14d1c84369b53f7e5b21eb343a.png#pic_center" srcset="/img/loading.gif" lazyload alt="[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aJWYkNig-1641100059067)(AndroidLearn-Handler.assets/image-20211109191727880.png)]"></p>
<p><code>layout_main.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=<span class="hljs-string">&quot;1.0&quot;</span> encoding=<span class="hljs-string">&quot;utf-8&quot;</span>?&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">LinearLayout</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">&quot;http://schemas.android.com/apk/res/android&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:orientation</span>=<span class="hljs-string">&quot;vertical&quot;</span>&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">TextView</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/tv_result&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;0.00&quot;</span> /&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">LinearLayout</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:orientation</span>=<span class="hljs-string">&quot;horizontal&quot;</span></span><br><span class="hljs-tag">        &gt;</span><br><br><br>        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/b_start&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;0dp&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_weight</span>=<span class="hljs-string">&quot;1&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_marginHorizontal</span>=<span class="hljs-string">&quot;10px&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;Start&quot;</span></span><br><span class="hljs-tag">            /&gt;</span><br><br>        <span class="hljs-tag">&lt;<span class="hljs-name">Button</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/b_stop&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;0dp&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_weight</span>=<span class="hljs-string">&quot;1&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:enabled</span>=<span class="hljs-string">&quot;false&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_marginHorizontal</span>=<span class="hljs-string">&quot;10px&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;Stop&quot;</span> /&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">LinearLayout</span>&gt;</span><br><br><span class="hljs-tag">&lt;/<span class="hljs-name">LinearLayout</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p><code>TimerCounterThread.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.example.ycc_task4_1;<br><br><span class="hljs-keyword">import</span> android.os.Bundle;<br><span class="hljs-keyword">import</span> android.os.Handler;<br><span class="hljs-keyword">import</span> android.os.Message;<br><br><span class="hljs-keyword">import</span> java.util.concurrent.atomic.AtomicBoolean;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TimerCounterThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Thread</span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">KEY_TIME_COUNTER</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;key_time_counter&quot;</span>;<br>    <span class="hljs-keyword">private</span> Handler handler;<br>    <span class="hljs-keyword">private</span> AtomicBoolean isRunning;<br>    <span class="hljs-keyword">private</span> <span class="hljs-type">float</span> timeCount=<span class="hljs-number">0.0f</span>;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">TimerCounterThread</span><span class="hljs-params">(Handler handler)</span> &#123;<br>        <span class="hljs-built_in">this</span>.handler = handler;<br>        isRunning = <span class="hljs-keyword">new</span> <span class="hljs-title class_">AtomicBoolean</span>(<span class="hljs-literal">false</span>);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>        <span class="hljs-built_in">super</span>.run();<br>        isRunning.set(<span class="hljs-literal">true</span>);<br>        <span class="hljs-keyword">while</span>(isRunning.get())&#123;<br>            <span class="hljs-keyword">try</span>&#123;<br>                Thread.sleep(<span class="hljs-number">100</span>);<br>                timeCount += <span class="hljs-number">0.10f</span>;<br>                sendCounter();<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e)&#123;<br>                e.printStackTrace();<br>            &#125;<br>        &#125;<br>    &#125;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">sendCounter</span><span class="hljs-params">()</span>&#123;<br>        <span class="hljs-type">Message</span> <span class="hljs-variable">mes</span> <span class="hljs-operator">=</span> handler.obtainMessage();<br>        <span class="hljs-type">Bundle</span> <span class="hljs-variable">bundle</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Bundle</span>();<br>        bundle.putFloat(KEY_TIME_COUNTER, timeCount);<br>        mes.setData(bundle);<br>        handler.sendMessage(mes);<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">stopTimer</span><span class="hljs-params">()</span>&#123;<br>        isRunning.set(<span class="hljs-literal">false</span>);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>

<p><code>MainActivity.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> androidx.annotation.NonNull;<br><span class="hljs-keyword">import</span> androidx.appcompat.app.AppCompatActivity;<br><br><span class="hljs-keyword">import</span> android.os.Bundle;<br><span class="hljs-keyword">import</span> android.os.Handler;<br><span class="hljs-keyword">import</span> android.os.Looper;<br><span class="hljs-keyword">import</span> android.os.Message;<br><span class="hljs-keyword">import</span> android.view.View;<br><span class="hljs-keyword">import</span> android.widget.Button;<br><span class="hljs-keyword">import</span> android.widget.TextView;<br><br><span class="hljs-keyword">import</span> java.util.concurrent.atomic.AtomicBoolean;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AppCompatActivity</span> &#123;<br>    Button b_start, b_stop;<br>    TextView tv;<br>    TimerCounterThread thread;<br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onCreate</span><span class="hljs-params">(Bundle savedInstanceState)</span> &#123;<br>        <span class="hljs-built_in">super</span>.onCreate(savedInstanceState);<br>        setContentView(R.layout.layout_main);<br>        b_start = findViewById(R.id.b_start);<br>        b_stop = findViewById(R.id.b_stop);<br>        tv = findViewById(R.id.tv_result);<br><br>        <span class="hljs-comment">// 创建 Handler</span><br>        <span class="hljs-keyword">final</span> <span class="hljs-type">Handler</span> <span class="hljs-variable">handler</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>(Looper.myLooper(), <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>.Callback()&#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">handleMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message message)</span> &#123;<br>                <span class="hljs-type">Bundle</span> <span class="hljs-variable">data</span> <span class="hljs-operator">=</span> message.getData();<br>                <span class="hljs-type">float</span> <span class="hljs-variable">timeCounter</span> <span class="hljs-operator">=</span> data.getFloat(TimerCounterThread.KEY_TIME_COUNTER);<br>                tv.setText(String.format(<span class="hljs-string">&quot;%.2f&quot;</span>, timeCounter));<br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>            &#125;<br>        &#125;);<br><br>        b_start.setOnClickListener(<span class="hljs-keyword">new</span> <span class="hljs-title class_">View</span>.OnClickListener() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onClick</span><span class="hljs-params">(View view)</span> &#123;<br>                thread = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TimerCounterThread</span>(handler);<br>                thread.start();<br>                b_start.setEnabled(<span class="hljs-literal">false</span>);<br>                b_stop.setEnabled(<span class="hljs-literal">true</span>);<br>            &#125;<br>        &#125;);<br>        b_stop.setOnClickListener(<span class="hljs-keyword">new</span> <span class="hljs-title class_">View</span>.OnClickListener() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onClick</span><span class="hljs-params">(View view)</span> &#123;<br>                thread.stopTimer();<br>                b_start.setEnabled(<span class="hljs-literal">true</span>);<br>                b_stop.setEnabled(<span class="hljs-literal">false</span>);<br>            &#125;<br>        &#125;);<br><br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<h2 id="8-3-获取网页内容"><a href="#8-3-获取网页内容" class="headerlink" title="8.3 获取网页内容"></a>8.3 获取网页内容</h2><p>首先需要在项目的 <code>mainifests/AndroidMainifest.xml</code> 里的 <code>&lt;application&gt;</code>标签添加</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">uses-permission</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">&quot;android.permission.INTERNET&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">uses-permission</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p> 允许项目进行网络访问</p>
<p><img src="https://img-blog.csdnimg.cn/637593c6e6724a9e84d409b68e35b5ac.png#pic_center" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>
<p><code>layout_main.xml</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-meta">&lt;?xml version=<span class="hljs-string">&quot;1.0&quot;</span> encoding=<span class="hljs-string">&quot;utf-8&quot;</span>?&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">LinearLayout</span> <span class="hljs-attr">xmlns:android</span>=<span class="hljs-string">&quot;http://schemas.android.com/apk/res/android&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">    <span class="hljs-attr">android:orientation</span>=<span class="hljs-string">&quot;vertical&quot;</span></span><br><span class="hljs-tag">    &gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">EditText</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/editText&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;https://www.baidu.com&quot;</span> /&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">Button</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/button&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;Get Web&quot;</span> /&gt;</span><br><br>    <span class="hljs-tag">&lt;<span class="hljs-name">ScrollView</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">        <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;match_parent&quot;</span>&gt;</span><br><br>        <span class="hljs-tag">&lt;<span class="hljs-name">LinearLayout</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">            <span class="hljs-attr">android:orientation</span>=<span class="hljs-string">&quot;vertical&quot;</span> &gt;</span><br><br>            <span class="hljs-tag">&lt;<span class="hljs-name">TextView</span></span><br><span class="hljs-tag">                <span class="hljs-attr">android:id</span>=<span class="hljs-string">&quot;@+id/tv_ack&quot;</span></span><br><span class="hljs-tag">                <span class="hljs-attr">android:layout_width</span>=<span class="hljs-string">&quot;match_parent&quot;</span></span><br><span class="hljs-tag">                <span class="hljs-attr">android:layout_height</span>=<span class="hljs-string">&quot;wrap_content&quot;</span></span><br><span class="hljs-tag">                <span class="hljs-attr">android:text</span>=<span class="hljs-string">&quot;&quot;</span> /&gt;</span><br>        <span class="hljs-tag">&lt;/<span class="hljs-name">LinearLayout</span>&gt;</span><br>    <span class="hljs-tag">&lt;/<span class="hljs-name">ScrollView</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">LinearLayout</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p><code>JsoupGetThread.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.example.ycc_task4_2;<br><br><span class="hljs-keyword">import</span> android.os.Bundle;<br><span class="hljs-keyword">import</span> android.os.Handler;<br><span class="hljs-keyword">import</span> android.os.Message;<br><br><span class="hljs-keyword">import</span> org.jsoup.Jsoup;<br><span class="hljs-keyword">import</span> org.jsoup.nodes.Document;<br><br><span class="hljs-keyword">import</span> java.io.IOException;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">JsoupGetThread</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Thread</span>&#123;<br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">String</span> <span class="hljs-variable">HTML_ACK</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;html_ack&quot;</span>;<br>    <span class="hljs-keyword">private</span> String url;<br>    <span class="hljs-keyword">private</span> Handler handler;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-title function_">JsoupGetThread</span><span class="hljs-params">(String url, Handler handler)</span> &#123;<br>        <span class="hljs-built_in">this</span>.url = url;<br>        <span class="hljs-built_in">this</span>.handler = handler;<br>    &#125;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">getMessage</span><span class="hljs-params">(Message mes)</span>&#123;<br>        <span class="hljs-type">Bundle</span> <span class="hljs-variable">data</span> <span class="hljs-operator">=</span> mes.getData();<br>        <span class="hljs-keyword">return</span> data.getString(HTML_ACK);<br>    &#125;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> &#123;<br>        String ack;<br>        <span class="hljs-keyword">try</span>&#123;<br>            <span class="hljs-type">Document</span> <span class="hljs-variable">doc</span> <span class="hljs-operator">=</span> Jsoup.connect(url).timeout(<span class="hljs-number">10000</span>).get();<br>            ack = doc.toString();<br>        &#125; <span class="hljs-keyword">catch</span> (IOException e)&#123;<br>            e.printStackTrace();<br>            ack = e.toString();<br>        &#125;<br>        <span class="hljs-type">Message</span> <span class="hljs-variable">mes</span> <span class="hljs-operator">=</span> handler.obtainMessage();<br>        <span class="hljs-type">Bundle</span> <span class="hljs-variable">bundle</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Bundle</span>();<br>        bundle.putString(HTML_ACK, ack);<br>        mes.setData(bundle);<br>        handler.sendMessage(mes);<br>    &#125;<br>&#125;<br><br></code></pre></td></tr></table></figure>



<p><code>MainActivity.java</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">import</span> androidx.annotation.NonNull;<br><span class="hljs-keyword">import</span> androidx.appcompat.app.AppCompatActivity;<br><br><span class="hljs-keyword">import</span> android.os.Bundle;<br><span class="hljs-keyword">import</span> android.os.Handler;<br><span class="hljs-keyword">import</span> android.os.Message;<br><span class="hljs-keyword">import</span> android.view.View;<br><span class="hljs-keyword">import</span> android.widget.Button;<br><span class="hljs-keyword">import</span> android.widget.EditText;<br><span class="hljs-keyword">import</span> android.widget.TextView;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">MainActivity</span> <span class="hljs-keyword">extends</span> <span class="hljs-title class_">AppCompatActivity</span> &#123;<br><br>    <span class="hljs-meta">@Override</span><br>    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onCreate</span><span class="hljs-params">(Bundle savedInstanceState)</span> &#123;<br>        <span class="hljs-built_in">super</span>.onCreate(savedInstanceState);<br>        setContentView(R.layout.layout_main);<br><br>        <span class="hljs-type">TextView</span> <span class="hljs-variable">tv</span> <span class="hljs-operator">=</span> findViewById(R.id.tv_ack);<br>        <span class="hljs-type">Handler</span> <span class="hljs-variable">handler</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Handler</span>.Callback()&#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">handleMessage</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> Message message)</span> &#123;<br>                <span class="hljs-type">String</span> <span class="hljs-variable">s</span> <span class="hljs-operator">=</span> JsoupGetThread.getMessage(message);<br>                tv.setText(s);<br>                <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;<br>            &#125;<br>        &#125;);<br>        <span class="hljs-type">EditText</span> <span class="hljs-variable">et</span> <span class="hljs-operator">=</span> findViewById(R.id.editText);<br>        <span class="hljs-type">Button</span> <span class="hljs-variable">bt</span> <span class="hljs-operator">=</span> findViewById(R.id.button);<br>        bt.setOnClickListener(<span class="hljs-keyword">new</span> <span class="hljs-title class_">View</span>.OnClickListener() &#123;<br>            <span class="hljs-meta">@Override</span><br>            <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">onClick</span><span class="hljs-params">(View view)</span> &#123;<br>                <span class="hljs-type">String</span> <span class="hljs-variable">url</span> <span class="hljs-operator">=</span> et.getText().toString();<br>                <span class="hljs-keyword">new</span> <span class="hljs-title class_">JsoupGetThread</span>(url, handler).start();<br>            &#125;<br>        &#125;);<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>


<h1 id="参考博文（侵删）"><a href="#参考博文（侵删）" class="headerlink" title="参考博文（侵删）"></a>参考博文（侵删）</h1><ul>
<li><p><a target="_blank" rel="noopener" href="https://www.cnblogs.com/zhujiabin/p/6906022.html">Android 为什么要有handler机制？handler机制的原理</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://developer.android.google.cn/reference/kotlin/java/lang/Thread">Android-Thread官方帮助文档</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2016/1014/6675.html">[译] 探索 Android 大杀器——Handler</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/fa1450b0bbf6">Android-handler</a></p>
</li>
<li><p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/8a44d4a819bc">理解AtomicBoolean</a></p>
</li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%AE%89%E5%8D%93/" class="category-chain-item">安卓</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Android/">#Android</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Android Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo</div>
      <div>http://example.com/2022/01/02/Android _ Handler多线程消息传递机制 _ Bundle封装数据 _ Message消息发送 +Demo/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>John Doe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年1月2日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/01/03/Spark%20Scala%E7%89%88%E6%9C%AC%20_%20%E9%80%89%E6%8B%A9%E9%A2%98%E6%B1%87%E6%80%BB/" title="Spark Scala版本 _ 选择题汇总">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Spark Scala版本 _ 选择题汇总</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/30/JavaWeb%20_%20JDBC%20_%20%E8%BF%90%E7%94%A8%E5%8F%8D%E5%B0%84%E5%92%8C%E6%B3%9B%E5%9E%8B%E6%9C%BA%E5%88%B6%E5%AE%9E%E7%8E%B0%E6%9F%A5%E8%AF%A2%E6%95%B0%E6%8D%AE%E8%A1%A8%E5%90%8E%E7%9B%B4%E6%8E%A5%E5%88%9B%E5%BB%BA%E6%8C%87%E5%AE%9A%E7%9A%84%E5%AF%B9%E8%B1%A1/" title="JavaWeb _ JDBC _ 运用反射和泛型机制实现查询数据表后直接创建指定的对象">
                        <span class="hidden-mobile">JavaWeb _ JDBC _ 运用反射和泛型机制实现查询数据表后直接创建指定的对象</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
